#!/bin/bash

if [ -z "${1}" ]
	then
		echo "Error: Missing arguments!"
		echo "Usage: sh ${0} <Youtube user> [Pattern] [test]"
		echo "Note that only the first argument is mandatory"
		exit 1
fi

USER="${1}"
PATTERN="${2}"
BASE="http://youtube.com"

fetch_video() {
	URL="${BASE}/watch?v=${1}"
	GET="${BASE}/get_video?"
	TITLE=$(wget -O - -q "${URL}"|egrep "<title>" | cut -b 19- | sed 's,........$,,g')
	wget -q -O - "${URL}"|grep -oE 'video_id=.*&t=[^\"&]*'|sed 1q|xargs -I{} wget -O "${TITLE}.flv" "${GET}"{}
}

get_title() {
	URL="${BASE}/watch?v=${1}"
        wget -O - -q "${URL}"|egrep "<title>" | cut -b 19- | sed 's,........$,,g'	
}

crawl() {
	URL="${BASE}${1}"
	P="${2}"
	wget -O - -q "${URL}"|egrep "<a href=\"\/watch\?v=.*\" onclick"|egrep "${P}"|cut -b 22-|cut -d"\"" -f1|sort -u|egrep ".{11}"
}

pages() {
	USR="${1}"
	URL="${BASE}/profile_videos?user=${USR}"
	echo "/profile_videos?user=${USR}&page=1"
	wget -O - -q "${URL}"|egrep "class=\"pagerNotCurrent\""|egrep "page=[0-9]"|egrep "[0-9]<\/a>"|cut -b 16-|awk '{print $1}'|sed -e 's/.$//g'
}

if [ -z "${2}" ]
	then
	echo "Attempting to download all videos by user ${USER}:\n"
else 
	echo "Attempting to download all videos by user ${USER} matching the pattern '${PATTERN}':\n"
fi

for page in $(pages "${USER}")
	do 
	for video in $(crawl "${page}" "${PATTERN}")
		do
		if [ "${3}" = "test" ]
			then
			echo " * ${video} as $(get_title "${video}").flv"
		else
			fetch_video "${video}"
		fi
		done
	done





